package com.edgar.thread.ch02;

import java.io.IOException;
import java.math.BigInteger;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import com.edgar.thread.annotation.GuardedBy;
import com.edgar.thread.annotation.ThreadSafe;

/**
 * 使用内部锁。 此类有性能问题
 * 
 * 每个java对象都可以用做一个实现同步的锁，这些锁称为内置锁或监视锁
 * 当某个线程请求一个由其他线程持有的锁时，发出请求的线程就会阻塞。然而由于内置锁是可以冲入的
 * 因此意味着获取锁的操作的粒度是”线程“，而不是”调用“。
 * @author Edgar Zhang
 * 
 */
@ThreadSafe
public class SynchronizedFactorizer extends HttpServlet {

	@GuardedBy("this")
	private BigInteger lastNumber;

	@GuardedBy("this")
	private BigInteger[] lastFactors;

	@Override
	public synchronized void service(ServletRequest request,
			ServletResponse response) throws ServletException, IOException {
		BigInteger i = extractFromRequest(request);
		if (i.equals(lastNumber)) {
			encodeIntoResponse(response, lastFactors);
		} else {
			BigInteger[] factors = factor(i);
			lastNumber = i;
			lastFactors = factors;
			encodeIntoResponse(response, factors);
		}
	}

	private void encodeIntoResponse(ServletResponse response,
			BigInteger[] factors) {
		// TODO Auto-generated method stub

	}

	private BigInteger[] factor(BigInteger i) {
		// TODO Auto-generated method stub
		return null;
	}

	private BigInteger extractFromRequest(ServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}
}